﻿
namespace Busconeitor.BusinessLayer.Utils
{
    using System.Linq;
    using Domain.Utils.SimpleList;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class HighlighResultMatchs
    {
        #region Atributos
        
        private const string IniRegex = "(";
        private const string EndRegex = ")";
        private const string MiddleRegex = ")|(";
        private const string IniHighligh = "<strong class= \"text-warning\" >";
        private const string EndHighligh = "</strong>";
        private Regex mPattern; 

        #endregion

        #region Constructores

        public HighlighResultMatchs(SimpleList pWords)
        {
            string[] origin = { "a", "e", "i", "o", "u" };
            string[] any = { "[aâãáàäÂÃÁÀÄ]+", "[eéèêëÉÈÊË]+", "[iíìîïÍÌÎÏ]+", "[oóòôõöÓÒÔÕÖ]+", "[uúùûüÚÙÛÜ]+" };

            var regex = new StringBuilder(IniRegex);
            pWords.StartIterator();

            while (pWords.HasNext())
            {
                var word = (string)pWords.Next();

                for (var i = 0; i < any.Length; i++)
                {
                    word = word.Replace(origin[i], any[i]);
                }

                regex.Append(word);
                regex.Append(MiddleRegex);
            }

            var pattern = regex.Replace(IniRegex, EndRegex, regex.Length - 1, 1);
            pattern = pattern.Remove(pattern.Length - 2, 2);
            mPattern = new Regex(pattern.ToString(), RegexOptions.IgnoreCase);
        }

        #endregion

        #region Propiedades

        #endregion
      
        #region Metodos

        /// <summary>
        /// Efectiviza el resaltado de un termino.
        /// </summary>
        /// <param name="pText"></param>
        /// <returns></returns>
        public string DoIt(string pText)
        {
            var result = new StringBuilder();
            result.Append(pText);
            
            var matcher = (from word in mPattern.Matches(pText).Cast<Match>()
                            select word.Value).Distinct();

            foreach (string match in matcher)
            {
                var matchString = match; 

                if (matchString.Length > 0)
                {
                    result.Replace(matchString, IniHighligh + match + EndHighligh);
                }
            }

            return result.ToString();
        } 

        #endregion
    }
}
